package com.hrm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hrm.mapper.DocumentMapper;
import com.hrm.pojo.Document;
import com.hrm.pojo.Users;
import com.hrm.service.DocumentService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Documented;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class DocumentServiceImpl implements DocumentService {
    @Autowired
    private DocumentMapper documentMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean addDocument(Document document) throws Exception {
        //获取token中的用户id
        Integer id = Integer.parseInt((String) request.getSession().getAttribute("id"));
        Users users = new Users();
        users.setId(id);
        document.setUsers(users);
        int row = documentMapper.insertSelective(document);
        if (row == 0) {
            throw new Exception("添加文档失败");
        }
        return true;
    }
    @Override
    public List<Document> findByTitle(Integer pageNum, Integer pageSize, String title) throws Exception {
        PageHelper.startPage(pageNum,pageSize);
        List<Document> documents = documentMapper.selectDocumentByTitle(title);
        if (documents.size() ==0) {
            throw  new Exception("没有找到相关文档");
        }
        return  documents;
    }

    @Override
    public Document findById(Integer id) throws Exception {
        Document document = documentMapper.selectByPrimaryKey(id);
        if(document==null){
            throw new Exception("获取文档失败");
        }
        return document;
    }

    @Override
    public boolean updateDocument(Document document) throws Exception {
        //判断文档是否存在
        Document result = documentMapper.selectByPrimaryKey(document.getId());
        if (result == null) {
            throw new Exception("文档不存在");
        }
        //更新文档
        int row = documentMapper.updateByPrimaryKeySelective(document);
        if (row == 0) {
            throw new Exception("更新文档失败");
        }
        return true;
    }

    @Override
    public boolean deleteDocument(ArrayList<Integer> documentIdList) throws Exception {
        for (Integer id : documentIdList) {
            if(documentMapper.deleteByPrimaryKey(id)<=0){
                throw new Exception("删除文档失败");
            }
        }
        return true;
    }

}
